<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDonationByIdAPI } from '@/services/donationDetail'
import type { DonationVo } from '@/types/home'
import { donationTypeStore } from '@/stores/modules/donationType'

// @ts-nocheck
// 使用ts-nocheck忽略整个文件的类型检查

// 系统信息相关
const statusBarHeight = ref(20)
const safeAreaInsetBottom = ref(0)

// 捐赠物ID
const props = defineProps({
  // 捐赠物ID
  donationId: {
    type: Number,
    default: null,
  },
  // 可直接传入捐赠物对象
  donationItem: {
    type: Object,
    default: null,
  },
})

// 事件
const emit = defineEmits(['close', 'cancel-order'])
//从持久层中获取捐赠物种类
const donationTypes = donationTypeStore().donationTypes
// 加载状态
const loading = ref(false)
// 捐赠物详情
const donationDetail = ref<DonationVo>({} as DonationVo)
// 当前展示的图片索引
const currentImageIndex = ref(0)
// 图片数组
const imageList = ref<string[]>([])

// 倒计时相关
const countdown = reactive({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
  timer: null as any,
})

// 状态映射
const statusMap: Record<number, string> = {
  0: '待审核',
  1: '已取消',
  2: '待入库',
  3: '已完成',
  4: '已完成', // 取货-已完成
  5: '特殊处理',
  6: '待取货',
}

// 获取状态文字
const getStatusText = computed(() => {
  const status = donationDetail.value.status || 0
  return statusMap[status] || '未知状态'
})

// 获取用户头像
const userAvatar = computed(() => {
  return donationDetail.value?.userImage || '/static/images/default-avatar.png'
})

// 获取用户名
const userName = computed(() => {
  return donationDetail.value?.donorName || '未知用户'
})

// 获取订单号
const orderNumber = computed(() => {
  return donationDetail.value?.oddNumber || donationDetail.value?.id || '未知订单'
})

// 获取物品种类
function getTypeName() {
  return (
    donationTypes.find((item) => item.id === donationDetail.value?.categoryId)?.typeName || '未分类'
  )
}

// 获取物品位置信息
const locationInfo = computed(() => {
  const houseName = donationDetail.value?.loveHouseName || '未指定'
  const deviceNumber = donationDetail.value?.goodsShelves.deviceNumber
  const shelfNumber = donationDetail.value?.goodsShelves.shelfNumber

  let result = houseName
  if (deviceNumber) {
    result += ` 设备号：${deviceNumber}`
  }
  if (shelfNumber) {
    result += ` 货架号：${shelfNumber}`
  }

  return result
})

// 获取系统信息
function getSystemInfo() {
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 20
      // 部分机型可能不支持safeAreaInsets
      if (res.safeAreaInsets) {
        safeAreaInsetBottom.value = res.safeAreaInsets.bottom || 0
      } else if (res.safeArea) {
        // 计算底部安全区域
        const screenHeight = res.screenHeight
        const safeAreaBottom = res.safeArea.bottom
        safeAreaInsetBottom.value = screenHeight - safeAreaBottom
      }
    },
  })
}

// 组件挂载时加载数据
onMounted(() => {
  // 获取系统信息设置导航栏
  getSystemInfo()

  // 如果传入了donationItem，直接使用
  if (props.donationItem) {
    donationDetail.value = props.donationItem as unknown as DonationVo
    if (donationDetail.value?.images) {
      imageList.value = donationDetail.value.images.split(',')
    }
    startCountdown()
  }
  // 如果传入了donationId，则请求详情
  else if (props.donationId) {
    loadDonationDetail(props.donationId)
  }
})

// 加载捐赠物详情
async function loadDonationDetail(id: number) {
  if (!id) return

  loading.value = true
  try {
    const res = await getDonationByIdAPI(id)
    if (res.code === 200 && res.data) {
      donationDetail.value = res.data
      // 处理图片列表
      if (donationDetail.value.images) {
        imageList.value = donationDetail.value.images.split(',')
      }
      // 开始倒计时计算
      startCountdown()
    } else {
      uni.showToast({
        title: '获取详情失败',
        icon: 'none',
      })
    }
  } catch (error) {
    console.error('获取捐赠物详情失败', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 是否可以取消订单（待审核或待入库状态）
const canCancel = computed(() => {
  const status = donationDetail.value?.status
  return status === 0 || status === 2
})

// 是否需要显示倒计时(待入库或待取货状态)
const needShowCountdown = computed(() => {
  const status = donationDetail.value?.status
  return status === 2 || status === 6
})

// 是否需要显示位置信息(待入库、待取货、取货已完成)
const needShowLocation = computed(() => {
  const status = donationDetail.value?.status
  return status === 2 || status === 6 || status === 3
})

// 开始倒计时
function startCountdown() {
  if (!donationDetail.value?.updateTime || !needShowCountdown.value) return

  // 清除之前的定时器
  if (countdown.timer) {
    clearInterval(countdown.timer)
    countdown.timer = null
  }

  // 计算截止时间（更新时间+1天）
  const updateTime = new Date(donationDetail.value.updateTime).getTime()
  const endTime = updateTime + 24 * 60 * 60 * 1000 // 加一天的毫秒数

  // 设置定时器，每秒更新倒计时
  countdown.timer = setInterval(() => {
    const now = Date.now()
    const diff = endTime - now

    if (diff <= 0) {
      // 倒计时结束
      countdown.days = 0
      countdown.hours = 0
      countdown.minutes = 0
      countdown.seconds = 0
      clearInterval(countdown.timer)
      countdown.timer = null
    } else {
      // 计算时间
      countdown.days = Math.floor(diff / (24 * 60 * 60 * 1000))
      countdown.hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
      countdown.minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000))
      countdown.seconds = Math.floor((diff % (60 * 1000)) / 1000)
    }
  }, 1000)
}

// 处理取消订单
function handleCancelOrder() {
  // 弹出输入框让用户输入取消原因
  uni.showModal({
    title: '取消订单',
    content: '',
    editable: true,
    placeholderText: '请输入取消原因',
    success: (res) => {
      if (res.confirm) {
        if (!res.content) {
          uni.showToast({
            title: '请输入取消原因',
            icon: 'none',
          })
          return
        }
        // 触发取消订单事件，传递订单id和取消原因
        emit('cancel-order', donationDetail.value?.id, res.content.trim())
      }
    },
  })
}

// 关闭详情
function handleClose() {
  emit('close')
}

// 格式化时间
function formatDate(dateString: Date) {
  if (!dateString) return ''

  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 图片预览
function previewImage(index: number) {
  uni.previewImage({
    current: index,
    urls: imageList.value,
  })
}

// 轮播图变化
function handleSwiperChange(e: any) {
  currentImageIndex.value = e.detail.current
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (countdown.timer) {
    clearInterval(countdown.timer)
    countdown.timer = null
  }
})

// 导出方法
defineExpose({
  loadDonationDetail,
})
</script>

<template>
  <view class="donation-detail" v-if="donationDetail">
    <!-- 导航栏 -->
    <view class="detail-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="back-btn" @tap="handleClose">
          <text class="iconfont icon-arrow-left"></text>
        </view>

        <!-- 导航栏中展示订单号 -->
        <view class="nav-info">
          <text class="nav-order-number">{{ orderNumber }}</text>
          <view class="nav-status" :class="`status-${donationDetail.status}`">
            {{ getStatusText }}
          </view>
        </view>

        <view class="right-placeholder"></view>
      </view>
      <!-- 标题下方的装饰线 -->
      <view class="header-line"></view>
    </view>

    <!-- 加载中 -->
    <view
      v-if="loading"
      class="loading-container"
      :style="{ paddingTop: statusBarHeight + 44 + 'px' }"
    >
      <view class="loading-indicator"></view>
      <text>加载中...</text>
    </view>

    <!-- 详情内容 -->
    <scroll-view v-else scroll-y class="detail-content">
      <!-- 捐赠人信息 - 移至最上方 -->
      <view class="user-info card-style">
        <image class="user-avatar" :src="userAvatar" mode="aspectFill"></image>
        <text class="user-name">{{ userName }}</text>
      </view>

      <!-- 倒计时(待入库或待取货) -->
      <view class="countdown-card card-style" v-if="needShowCountdown">
        <view class="countdown-title">
          {{ donationDetail.status === 2 ? '入库倒计时' : '取货倒计时' }}
        </view>
        <view class="countdown-timer">
          <view class="time-group">
            <view class="time-unit">
              <text class="time-value">{{ countdown.days }}</text>
            </view>
            <text class="time-label">天</text>
          </view>
          <text class="time-separator">:</text>
          <view class="time-group">
            <view class="time-unit">
              <text class="time-value">{{ countdown.hours.toString().padStart(2, '0') }}</text>
            </view>
            <text class="time-label">时</text>
          </view>
          <text class="time-separator">:</text>
          <view class="time-group">
            <view class="time-unit">
              <text class="time-value">{{ countdown.minutes.toString().padStart(2, '0') }}</text>
            </view>
            <text class="time-label">分</text>
          </view>
          <text class="time-separator">:</text>
          <view class="time-group">
            <view class="time-unit">
              <text class="time-value">{{ countdown.seconds.toString().padStart(2, '0') }}</text>
            </view>
            <text class="time-label">秒</text>
          </view>
        </view>
        <view class="countdown-note">
          <text class="countdown-icon">!</text>
          {{
            donationDetail.status === 2
              ? '请在规定时间内完成入库，否则订单将被自动取消'
              : '请在规定时间内完成取货，否则将视为放弃'
          }}
        </view>
      </view>

      <!-- 物品信息卡片 -->
      <view class="donation-info-container">
        <!-- 物品图片轮播 -->
        <view class="image-carousel card-style" v-if="imageList.length > 0">
          <swiper
            class="swiper"
            :indicator-dots="false"
            :autoplay="false"
            :circular="true"
            @change="handleSwiperChange"
          >
            <swiper-item
              v-for="(image, index) in imageList"
              :key="index"
              @tap="previewImage(index)"
            >
              <image :src="image" mode="aspectFill" class="carousel-image"></image>
            </swiper-item>
          </swiper>
          <view class="image-counter"> {{ currentImageIndex + 1 }}/{{ imageList.length }} </view>
          <!-- 添加左右指示器 -->
          <view v-if="imageList.length > 1" class="carousel-indicators">
            <view
              v-for="(_, index) in imageList"
              :key="index"
              class="indicator-dot"
              :class="{ active: currentImageIndex === index }"
            ></view>
          </view>
        </view>

        <!-- 物品信息 -->
        <view class="donation-info card-style">
          <view class="info-title">物品信息</view>
          <view class="info-item">
            <text class="item-label">物品种类</text>
            <text class="item-value">{{ getTypeName() }}</text>
          </view>
          <view class="info-item">
            <text class="item-label">物品描述</text>
            <text class="item-value desc-text">{{ donationDetail.description || '暂无描述' }}</text>
          </view>
          <view class="info-item" v-if="donationDetail.updateTime">
            <text class="item-label">更新时间</text>
            <text class="item-value">{{ formatDate(donationDetail.updateTime) }}</text>
          </view>

          <!-- 入库时间(已完成) -->
          <view class="info-item" v-if="donationDetail.storageTime">
            <text class="item-label">入库时间</text>
            <text class="item-value">{{ formatDate(donationDetail.storageTime) }}</text>
          </view>

          <!-- 取消原因(已取消) -->
          <view class="info-item" v-if="donationDetail.cancelReason">
            <text class="item-label">取消原因</text>
            <text class="item-value">{{ donationDetail.cancelReason }}</text>
          </view>

          <!-- 物品位置信息(待入库、待取货、取货已完成) -->
          <view class="info-item" v-if="needShowLocation">
            <text class="item-label">物品位置</text>
            <text class="item-value location-text">{{ locationInfo }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮区域 -->
      <view
        class="action-area"
        v-if="canCancel"
        :style="{ paddingBottom: safeAreaInsetBottom + 'px' }"
      >
        <button class="cancel-btn" @tap="handleCancelOrder">取消订单</button>
      </view>
    </scroll-view>

    <!-- 底部空白区域，保证能滑动到最底部的内容 -->
    <view class="bottom-safe-area" :style="{ height: safeAreaInsetBottom + 'px' }"></view>
  </view>
</template>

<style lang="scss">
.donation-detail {
  background-color: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  // 头部导航
  .detail-header {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;

    .nav-content {
      height: 44px;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
    }

    .header-line {
      height: 1px;
      background: linear-gradient(to right, transparent, #e0e0e0, transparent);
      margin-top: 4rpx;
    }

    .back-btn {
      width: 70rpx;
      height: 70rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(240, 240, 240, 0.6);
      border-radius: 50%;

      .iconfont {
        font-size: 38rpx;
        color: #333;
      }
    }

    // 导航栏中的订单信息
    .nav-info {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding: 0 20rpx;

      .nav-order-number {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-right: 20rpx;
      }

      .nav-status {
        font-size: 24rpx;
        font-weight: bold;
        padding: 4rpx 16rpx;
        border-radius: 30rpx;

        &.status-0 {
          color: #e6a23c;
          background-color: #fdf6ec;
        }

        &.status-1 {
          color: #f56c6c;
          background-color: #fef0f0;
        }

        &.status-2 {
          color: #409eff;
          background-color: #ecf5ff;
        }

        &.status-3,
        &.status-4 {
          color: #67c23a;
          background-color: #f0f9eb;
        }

        &.status-5 {
          color: #909399;
          background-color: #f4f4f5;
        }

        &.status-6 {
          color: #e6a23c;
          background-color: #fdf6ec;
        }
      }
    }

    .right-placeholder {
      width: 70rpx;
    }
  }

  // 加载中
  .loading-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .loading-indicator {
      width: 80rpx;
      height: 80rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #4a69bd;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
  }

  // 详情内容
  .detail-content {
    flex: 1;
    padding: 30rpx;
    padding-top: 0;
    // 增加顶部外边距，确保不被导航栏遮挡
    margin-top: calc(44px + v-bind(statusBarHeight) + 20rpx);

    // 卡片公共样式
    .card-style {
      background-color: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 30rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    }

    // 捐赠人信息 - 显示在最上方
    .user-info {
      display: flex;
      align-items: center;
      background: linear-gradient(to right, #fff, #f9f9f9);
      border-left: 8rpx solid #4a69bd;

      .user-avatar {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        background-color: #f5f5f5;
        border: 4rpx solid rgba(74, 105, 189, 0.1);
      }

      .user-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }

    // 倒计时卡片样式
    .countdown-card {
      background: linear-gradient(135deg, #4a69bd, #6c87d3);
      color: #fff;

      .countdown-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 24rpx;
        text-align: center;
        color: #fff;
      }

      .countdown-timer {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 24rpx;

        .time-group {
          display: flex;
          flex-direction: column;
          align-items: center;
        }

        .time-unit {
          width: 70rpx;
          height: 70rpx;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 10rpx;
          margin-bottom: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          backdrop-filter: blur(5px);

          .time-value {
            color: #fff;
            font-size: 34rpx;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .time-label {
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.9);
        }

        .time-separator {
          font-size: 36rpx;
          font-weight: bold;
          color: #fff;
          margin: 0 12rpx;
          margin-bottom: 30rpx;
        }
      }

      .countdown-note {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #fff;
        background-color: rgba(255, 255, 255, 0.2);
        padding: 16rpx;
        border-radius: 10rpx;
        backdrop-filter: blur(5px);

        .countdown-icon {
          display: inline-block;
          width: 32rpx;
          height: 32rpx;
          line-height: 32rpx;
          text-align: center;
          background-color: rgba(255, 255, 255, 0.9);
          color: #4a69bd;
          border-radius: 50%;
          margin-right: 10rpx;
          font-weight: bold;
        }
      }
    }

    // 物品信息容器
    .donation-info-container {
      // 物品图片轮播
      .image-carousel {
        overflow: hidden;
        position: relative;
        padding: 0;
        border-radius: 20rpx;

        .swiper {
          height: 500rpx;
          border-radius: 20rpx;
          overflow: hidden;

          .carousel-image {
            width: 100%;
            height: 100%;
            transition: transform 0.3s;

            &:active {
              transform: scale(0.98);
            }
          }
        }

        .image-counter {
          position: absolute;
          right: 20rpx;
          top: 20rpx;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          font-size: 24rpx;
          padding: 8rpx 20rpx;
          border-radius: 30rpx;
        }

        .carousel-indicators {
          position: absolute;
          bottom: 20rpx;
          left: 0;
          right: 0;
          display: flex;
          justify-content: center;

          .indicator-dot {
            width: 16rpx;
            height: 16rpx;
            background-color: rgba(255, 255, 255, 0.5);
            border-radius: 50%;
            margin: 0 8rpx;
            transition: all 0.3s;

            &.active {
              width: 24rpx;
              background-color: #fff;
              border-radius: 8rpx;
            }
          }
        }
      }

      // 物品信息
      .donation-info {
        .info-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 24rpx;
          position: relative;

          &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: -10rpx;
            width: 60rpx;
            height: 4rpx;
            background-color: #4a69bd;
            border-radius: 2rpx;
          }
        }

        .info-item {
          display: flex;
          margin-bottom: 24rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .item-label {
            width: 160rpx;
            font-size: 28rpx;
            color: #999;
            flex-shrink: 0;
          }

          .item-value {
            flex: 1;
            font-size: 28rpx;
            color: #333;

            &.desc-text {
              white-space: pre-wrap;
              word-break: break-all;
              line-height: 1.5;
            }

            &.location-text {
              color: #409eff;
              font-weight: 500;
            }
          }
        }
      }
    }

    // 操作按钮区域
    .action-area {
      margin-top: 60rpx;
      margin-bottom: 60rpx;
      padding: 0 40rpx;

      .cancel-btn {
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        color: #fff;
        background: linear-gradient(to right, #f56c6c, #ff9a9e);
        text-align: center;
        box-shadow: 0 6rpx 12rpx rgba(245, 108, 108, 0.2);
        position: relative;
        overflow: hidden;

        &:active::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}
</style>
